package com.mostromas.ess.system.api;

import com.mostromas.ess.entities.UserProject;
import com.mostromas.ess.feign.IFeignProjectController;
import com.mostromas.ess.system.req.RegisterREQ;
import com.mostromas.ess.system.service.ISysUserService;
import com.mostromas.ess.util.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.PrintWriter;

@Api(value = "用户管理接口", description = "用户管理接口,不用通过身份认证即可调用接口")
@RestController
@RequestMapping("/api/user")
public class ApiSysUserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IFeignProjectController feignProjectController;

    @ApiImplicitParam(name = "username", value = "用户名", required = true)
    @ApiOperation("校验用户名是否存在")
    @GetMapping("/username/{username}")
    public Result checkUsername(@PathVariable("username") String username) {
        Result result = sysUserService.checkUsername(username);
        return result;
    }

    @ApiOperation("注册用户接口")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterREQ req) {

        System.out.println(req.getPassword());
        Result result = sysUserService.register(req);
        return result;
    }

    @ApiOperation("用户修改密码接口")
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody RegisterREQ req){
        if(StringUtils.isEmpty(req.getUsername())) {
            return Result.error("用户名不能为空,请重试");
        }
        if(req.getUsername().length() < 5) {
            return Result.error("用户名长度不能小于5");
        }
        if(StringUtils.isEmpty(req.getPassword())) {
            return Result.error("新密码不能为空,请重试");
        }
        if(req.getPassword().length() < 6) {
            return Result.error("密码长度不能小于6");
        }
        if(StringUtils.isEmpty(req.getRepPassword())) {
            return Result.error("确认密码不能为空,请重试");
        }
        if(!req.getPassword().equals(req.getRepPassword())) {
            return Result.error("密码不一致,请重试");
        }
        //通过用户名、硬件ID、软件ID查询是否在常用地登陆
        UserProject up = feignProjectController.getUserProject(req.getUsername(),req.getProjectId(),req.getHardwareCoding());
        if(up == null){
            return Result.error("请在注册时的电脑上修改密码");
        }

        return sysUserService.resetPassword(req);
    }
}
